<template>
  <!--yz_pay 包括支付需要的弹窗和消费红包弹窗-->
  <div style="margin-bottom: 3rem;">
    <template v-if="payType">
      <van-radio-group v-model="radio" @change="radioChange">

      <div class="mod_btns" v-for="(btn, i) in payType" :key="i" v-show="!popupSpecs">
        <a class="mod_btn" @click.stop="clickPayRadio(btn)">
          <template v-if="btn.icon">
            <i class="iconfont" :class="btn.icon.icon_url" :style="{'color': btn.icon.color, 'fontSize': '28px','margin-right': '.75rem'} " v-if="btn.icon.icon_url"></i>
            <img class="icon_img" :src="btn.icon.icon_img" v-if="btn.icon.icon_img"/>
          </template>
          <i class="iconfont icon-pay_default" v-else></i>
          <div style="display: flex; flex-direction: column;">
            <span>{{ btn.name }}</span>
            <span v-if="balanceNum_store && btn.value == 80">{{ $i18n.t('base.available') }}:<span style="color: 'var(--themeBaseColor)';">{{balanceNum_store}}</span>{{ $i18n.t('元') }}</span>
            <span v-if="btn.other && btn.other.usable">
              {{ $i18n.t('base.available') }} <span style="color: 'var(--themeBaseColor)';">{{btn.other.usable}}</span>{{ $i18n.t('元') }}
              <template v-if="btn.other.recharge_order_pay">,差 <span style="color: 'var(--themeBaseColor)';">{{ lackNum(btn.other.usable) }}</span>元</template>
            </span>
            <span class="f-12 themeColor flex-a-c" v-if="btn.other && btn.other.child_pay && btn.other.child_pay.child_pay_status ">
              {{ selectSubMerchant && selectSubMerchant.name || '请选择账号' }} <i class="iconfont icon-advertise-next"></i>
            </span>
          </div>
          <span  v-if="btn.value == 103 && radioCurrency && radioCurrency.currency_name">（{{ radioCurrency.currency_name }}）</span>
          <img class="icon_img" :src="btn.icon && btn.icon.unionpay" v-if="btn.icon && btn.icon.unionpay" style="height: 1.5rem;margin-left: 0.5rem;"/>
        </a>
        <van-radio :name="btn.value" checked-color="var(--themeBaseColor)" v-if="!(btn.value == 3 && btn.other.recharge_order_pay)"></van-radio>

        <div v-if="btn.value == 3 && btn.other.recharge_order_pay" class="recharge-btn-text f-13" @click.stop="toRecharge">
          充值并支付
        </div>

        <div class="activityItem " v-if="btn.other && btn.other.sale && btn.other.recharge_order_pay" @click.stop="toRecharge">
          <div class="acitem" v-for="(item, index) in btn.other.sale" :key="index">
            <div class="left f-16"><small class="f-12">{{ $i18n.t("money") }}</small>{{ item.enough }}</div>
            <div class="right f-11">赠送{{ item.give }}{{ btn.other.proportion_status == '0'? '元': '%' }}</div>
          </div>
        </div>
      </div>
      </van-radio-group>

    </template>
    <div v-if="this.payType.length!==0" @click="submit" class="newSubTn" :class="[fun.getPhoneEnv() == 3 ? 'pcStyle' : '']">{{ $i18n.t('base.payNow') }}</div>
    <pay-keyboard :payKeyboardShow.sync="popupSpecs" @complete="onInput" @close="changePopupSpecs"></pay-keyboard>

    <van-popup v-model="showQR" :style="{ width: '80%' }">
      <img style="width: 15rem; height: 15rem; padding: 1rem;" :src="qrcode" alt=""/>
      <p style="font-weight: bold; font-size: 16px; padding-bottom: 0.5rem;">请用微信识别二维码支付</p>
    </van-popup>

    <van-popup v-model="showZFBQR" :style="{ width: '80%' }">
      <div v-show="isZFBQR">
        <canvas id="qrccode-canvas"></canvas>
        <p style="font-weight: bold; font-size: 16px; padding-bottom: 0.5rem;">请用支付宝识别二维码支付</p>
      </div>
      <p v-show="!isZFBQR" style="font-weight: bold; font-size: 16px; padding: 3rem;">正在为您生成二维码中，请稍后...</p>
    </van-popup>

    <!--消费红包-->
    <van-overlay :show="showPacket" @click="closePacket">
      <div class="wrapper">
        <div class="block" @click.stop>
          <img @click="toPacket" src="../../assets/images/consume_packet.png"/>
        </div>
      </div>
    </van-overlay>

    <van-popup v-model="walletCurrencyShow" round closeable :style="{ width: '85%' }">
      <van-nav-bar title="选择支付币种"></van-nav-bar>
      <van-radio-group v-model="radioCurrency" class="wallet-currency-group" @change="changeRadioCurrency">
        <van-cell-group v-for="item in walletCurrency" :key="item.currency">
          <van-cell :title="item.currency_name" clickable @click="radioCurrency = item" :border='false'>
            <template #right-icon>
              <van-radio :name="item" checked-color="var(--themeBaseColor)"/>
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
      <van-button type="danger" block @click="submit">立即支付</van-button>
    </van-popup>

    <van-popup v-model="isShowCodeQRPay" round :style="{ width: '70%',left: '50%' }" @close='closeCodeQRPay'>
      <div v-show="isCodeQRPay">
        <canvas id="qrPay-canvas"></canvas>
        <img :src="QRPayImg" alt="">
        <p style="font-weight: bold; font-size: 16px; padding-bottom: 0.5rem;">请用{{payQRInfo.text}}识别二维码支付</p>
      </div>
      <p v-show="!isCodeQRPay" style="font-weight: bold; font-size: 16px; padding: 3rem;">正在为您生成二维码中，请稍后...</p>
    </van-popup>

    <van-popup v-model="subMerchantPop" class="pop-base-class" position="bottom" round style="background-color: #F5F5F5;" closeable>
      <div class="pop-base-title">选择账号</div>
      <div class="pop-base-content t-l">
        <van-radio-group v-model="selectSubMerchant" class="wallet-currency-group" @change="changeSubMerchantID">
          <van-cell-group >
            <van-cell :title="item.name" clickable @click="selectSubMerchant = item" :border='false' v-for="item in SubMerchantData" :key="item.id">
              <template #right-icon>
                <van-radio :name="item" checked-color="var(--themeBaseColor)"/>
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </div>
      <div class="pop-base-bottom flex" @click="subMerchantPop = false">
        <van-button round type="danger" block color="var(--themeBaseColor)" style="height: 40px;">确认</van-button>
      </div>
    </van-popup>

  </div>
</template>

<script>
import payKeyboard from "components/payKeyboard";
import QRCode from "qrcode";
export default {
  props: ["payType", "typename", "popupSpecs", "showQR", "qrcode", "showZFBQR", "isZFBQR", "showPacket","balanceNum",
    "balanceNum_store","payTag","showCodeQRPay","order_pay_id","orderNum"],
  data() {
    return {
      payarr: "",
      radio:'',
      submitArr:'',
      walletCurrencyShow: false,
      radioCurrency: null,
      isCodeQRPay: '',
      payQRInfo: {},
      isShowCodeQRPay: false,

      subMerchantPop: false,
      SubMerchantData: [],
      selectSubMerchant: null,

    };
  },
  components: { payKeyboard },
  mounted() {
    if(this.payType && this.payType.length > 0) {
      if(this.payType[0].other.recharge_order_pay && this.payType.length > 1) {
        this.submitArr = this.payType[1];
        this.radio = this.payType[1].value;
      } else {
        this.submitArr = this.payType[0];
        this.radio = this.payType[0].value;
      }

    }
  },
  watch: {
    payType(val) {
      // 监听变化后的改动
      if(val && val.length > 0) {
        this.submitArr = val[0];
        this.radio = val[0].value;
      }
    },
    showCodeQRPay(val){
      this.isShowCodeQRPay = val;
      if(val){
        return this.getPayQR();
      }
      if(this.intervalPayQR) clearInterval(this.intervalPayQR);
    }
  },
  activated(){
    this.submitArr = '';
    this.radio = '';
  },
  methods: {
    toRecharge(){
      if (JSON.parse(window.localStorage.getItem("globalParameter")).ios_virtual_pay == "1" && this.fun.isIphone()) {
        this.$dialog.alert({
          message: "十分抱歉，由于相关规定，你暂时无法在这里充值！"
        });
        return false;
      }
      this.$emit("updateData",'isShowRecharge',true);
    },
    closeCodeQRPay(){
      this.isShowCodeQRPay = false;
      this.$parent.showCodeQRPay = false;
    },
    radioChange(e){
      for(let key  in this.payType){
        if(this.payType[key].value == e){
          this.submitArr = this.payType[key];
          this.radio = this.payType[key].value;
        }
      }
      if(e == 103) {
        // 钱包app 币种
        this.getCurrency();
      }
      this.getSubMerchant(this.submitArr);
    },

    submit() {
      this.$emit("submit", this.submitArr);
    },
    toPacket() {
      this.$router.replace(this.fun.getUrl("ConsumePacketSuccess", {}, { order_id: this.order_ids }));
    },
    closePacket() {
      this.$emit("closePacket");
    },
    changePopupSpecs(flag) {
      this.payarr = "";
      this.$emit("changePopupSpecs", false);
    },
    onInput(e) {
      // if (this.payarr.length < 6) {
      //   this.payarr = `${this.payarr}${e}`;
      //   if (this.payarr.length == 6) {
      //     this.keyboardDone(this.payarr);
      //   }
      // }
      this.keyboardDone(e);
    },
    keyboardDone(val) {
      this.$emit("changePopupSpecs", false);
      this.getVerifyPassword(val);
    },

    // 验证密码
    getVerifyPassword(pwd) {
      // order.pay.wechatPay
      $http.get("payment.password.check", { password: pwd }, "").then(
        (response) => {
          if (response.result == 1) {
            this.$emit("balancePay", pwd,this.payTag,this.radio);
          } else {
            this.$dialog
              .confirm({ message: response.msg })
              .then(() => {
                if (response.data.code == 2001) {
                  // 商城支付密码设置未开启
                  // this.$router.go(-1)
                } else if (response.data.code == 2002) {
                  // 用户未设置支付密码
                  // 去设置密码
                  this.$router.push(this.fun.getUrl("set_balance_password", {}));
                } else if (response.data.code == 2003) {
                  // 支付密码错误,重新输入
                  this.payarr = "";
                  this.$emit("changePopupSpecs", true);
                }
              })
              .catch(() => {
                if (response.data.code == 2001) {
                  // 商城支付密码设置未开启
                } else if (response.data.code == 2002) {
                  // 用户未设置支付密码
                } else if (response.data.code == 2003) {
                  // 支付密码错误
                }
              });
          }
        });
    },
    clickPayRadio(btn){
      this.radio = btn.value;
      if(btn.value == 103) {
        // 钱包app 币种
        this.getCurrency();
      }
      this.getSubMerchant(btn);
    },
    getSubMerchant(btn){
      if(btn.other && btn.other.child_pay && btn.other.child_pay.child_pay_status ){
        if(!this.SubMerchantData.length) this.SubMerchantData = btn.other.child_pay.child_pay_list;
        if(!this.selectSubMerchant) this.selectSubMerchant = btn.other.child_pay.child_pay_list[0];
        this.subMerchantPop = true;
      }
    },
    async getCurrency(){
      //获取币种列表
      let { result, msg, data } = await $http.get("plugin.love-speed-pool.frontend.wallet-pay.get-currency",{},".");
      if (result == 0) return this.$toast(msg);
      this.walletCurrency = data;
      this.radioCurrency = data[0];
      this.$parent.radioCurrency = data[0];
      this.walletCurrencyShow = true;//显示币种选择弹窗
    },
    changeRadioCurrency(e){
      this.$parent.radioCurrency = e;
    },
    changeSubMerchantID(e){
      this.$parent.selectSubMerchant = e;
    },
    async getPayQR() {
      switch (this.radio) {
      case 85:
        this.payQRInfo = {
          url: 'order.merge-pay.leshua-alipay',
          qrLinkPath: 'pay_msg.link',
          text: '支付宝'
        };
        break;
      case 57:
        this.payQRInfo = {
          url: 'order.merge-pay.wechat-native',
          qrLinkPath: 'code_url',
          text: '微信'
        };
        break;
      case 2:
        this.payQRInfo = {
          url: 'order.merge-pay.alipay',
          qrLinkPath: '',
          extinfo: {
            scan_pay: 1
          },
          text: '支付宝'
        };
        break;
      case 120:
        this.payQRInfo = {
          url: 'order.merge-pay.huibei-code-pay',
          qrLinkPath: 'qrcode',
          extinfo: {},
          text: '惠呗支付'
        };
        break;
      default:
        break;
      }
      let _params = {
        order_pay_id: this.order_pay_id
      };
      if(this.payQRInfo.extinfo) _params = {..._params,...this.payQRInfo.extinfo};
      let { result, msg, data } = await $http.get(this.payQRInfo.url,_params,".");
      if (result == 0) return this.$toast(msg);
      QRCode.toCanvas(document.getElementById("qrPay-canvas"), data[this.payQRInfo.qrLinkPath]||data, error => {
        if (error) {
          console.log(error);
          this.$toast(`生成${this.payQRInfo.text}支付二维码失败！`);
        } else {
          this.isCodeQRPay = true;
        }
      });
      // 轮询查询订单状态
      this.pollOrderStatus(this.order_pay_id);
    },
    pollOrderStatus(paymentId) {
      // 轮询查询订单状态的逻辑
      // 使用定时器每隔一段时间调用查询接口，直到订单支付状态改变
      this.intervalPayQR = setInterval(() => {
        // 调用查询接口
        this.checkOrderStatus(paymentId)
          .then((data) => {
            if (data.status) {
              // 订单支付状态已改变，执行回调
              clearInterval(this.intervalPayQR); // 停止轮询
              this.handlePaymentSuccess();
            }
          })
          .catch((error) => {
            this.$dialog.alert({ message: '查询订单状态失败' });
            console.error('查询订单状态失败', error);
            clearInterval(this.intervalPayQR); // 停止轮询
          });
      }, 2500); // 每隔2.5秒查询一次订单状态
    },
    async checkOrderStatus(paymentId) {
      // 查询订单状态的逻辑
      let { result, msg, data } = await $http.get('order.merge-pay.check-order-pay',{order_pay_id: paymentId},".");
      // 返回一个Promise，处理接口请求成功和失败的情况
      return new Promise((resolve, reject) => {
        // 调用查询订单状态接口
        if(result == 1) return resolve(data);
        this.$toast(msg);
        reject();
      });
    },
    handlePaymentSuccess() {
      // 订单支付成功后的回调逻辑
      this.outLogin();
      window.localStorage.removeItem("share_path");
      this.$dialog.alert({
        message: '订单支付成功',
      }).then(() => {
        this.$router.replace(this.fun.getUrl("home", {},{mid: 0}));
      });
    },
    async outLogin(){
      let { result, msg, data } = await $http.get('member.logout.index',{},".");
      if (result == 0) return this.$toast(msg);
      this.$store.commit("savemodel", {});
      window.localStorage.setItem("token", "");
      window.localStorage.setItem("loginUid", "");
      window.localStorage.removeItem('uid');
      window.firstLogin = 0;
      clearLoginData(); // 方法在index.html
    },
    lackNum(balance){
      //计算余额支付订单差价
      return (this.orderNum - balance).toFixed(2);
    }
  }
};
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
.pop-base-class {
  .pop-base-title {
    margin: 18px 12px 12px;
    font-size: 1rem;
    font-weight: bold;
    text-align: left;
  }
  .pop-base-content {
    min-height: 45vh;
    max-height: 55vh;
    overflow: scroll;
    padding: 0 0.75rem 5rem;
  }
  .pop-base-bottom {
    padding: 0.625rem 0.875rem;
    background: #ffffff;
  }
}
  .newSubTn {
    width: 80%;
    height: 3rem;
    position: fixed;
    bottom: 1rem;
    left: 10%;
    border-radius: 0.3rem;
    background-color: var(--themeBaseColor);
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .mod_btns {
    margin: 0 0.75rem;
    border-bottom: solid 1px #f4f4f4;
    text-align: left;
    padding-bottom: 0.875rem;
    padding-top: 0.875rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;

    .fa {
      font-size: 18px;
      color: #999;
    }

    .mod_btn {
      display: flex;
      align-items: center;
      flex: 1;
    }
  }
  .recharge-btn-text {
    text-align: center;
    width: 90px;
    line-height: 32px;
    border-radius: 18px 18px 18px 18px;
    border: 1px solid var(--themeBaseColor);
    color: var(--themeBaseColor);
  }

  .mod_btns:last-child {
    border-bottom: none;
  }

  .ispaskey {
    .van-number-keyboard {
      position: relative;
    }
  }

  #alipay-detail {
    background: rgba(0, 0, 0, 0.8);
    height: 100%;
    position: fixed;
    width: 100%;
    top: 0;
    left: 0;
    z-index: 100;

    img {
      width: 100%;
      position: relative;
      top: -2.5rem;
    }
  }

  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;

    .block {
      width: 14rem;
      height: 18rem;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .pcStyle {
    width: 375px;
    margin: 0 auto;
    left: 50% !important;
    margin-left: -187.5px;
  }

  .wallet-currency-group {
    text-align: left;
    max-height: 15rem;
    min-height: 10rem;
    overflow: scroll;

    .van-cell-group::after {
      border: none;
    }
  }
  .activityItem {
    width: 100%;
    overflow-x: scroll;
    display: flex;
    text-align: center;
    margin: 10px 20px 0 30px;
    /* 隐藏滚动条 */
    scrollbar-width: none; /* firefox */
    -ms-overflow-style: none; /* IE 10+ */

    .acitem {
      flex-shrink: 0;
      width: 100px;
      margin-right: 10px;
      font-size: 0.625rem;
      padding: 0.375rem 0;
      border-radius: 12px 12px 12px 12px;
      border: 1px solid #D6D6DC;
      display: flex;
      flex-direction: column;
      justify-content: center;
      color: var(--themeBaseColor);
      .right {
        color: #6E6E79;
      }
    }
  }
  .icon_img{
    width: 1.75rem;
    height: 1.75rem;
    margin: 0 0.75rem 0 0;
    display: block;
    object-fit: contain;
  }
</style>